package com.weifly.weistock.web.controller;

import com.weifly.weistock.rotation.bo.RotationConfigBO;
import com.weifly.weistock.core.common.Result;
import com.weifly.weistock.core.util.WeistockUtils;
import com.weifly.weistock.rotation.RotationMonitorService;
import com.weifly.weistock.rotation.RotationConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 轮动监控
 *
 * @author weifly
 * @since 2020/12/01
 */
@Controller
@RequestMapping(value = "/rotation")
public class RotationController {

    private Logger log = LoggerFactory.getLogger(RotationController.class);

    @Autowired
    private RotationMonitorService rotationMonitorService;

    /**
     * 轮动首页
     */
    @RequestMapping(value = "/index")
    public String index(HttpServletRequest request, HttpServletResponse response) {
        return "rotation/rotation";
    }

    /**
     * 编辑轮动配置
     */
    @RequestMapping(value = "/editRotationConfig")
    public String editRotationConfig(HttpServletRequest request) {
        RotationConfigBO rotationConfig = this.rotationMonitorService.getRotationConfig();
        if (rotationConfig != null) {
            request.setAttribute("rotationConfig", WeistockUtils.toJsonString(rotationConfig));
        }
        return "rotation/editRotationConfig";
    }

    /**
     * 更新轮动配置
     */
    @ResponseBody
    @RequestMapping("/updateRotationConfig")
    public Result updateRotationConfig(HttpServletRequest request) {
        try {
            RotationConfigBO rotationConfig = new RotationConfigBO();
            Result errorResult = RotationConverter.convertToRotationConfig(request, rotationConfig);
            if (errorResult != null) {
                return errorResult;
            }
            this.rotationMonitorService.updateRotationConfig(rotationConfig, true);
            return Result.createSuccessResult(null);
        } catch (Exception e) {
            log.error("更新轮动配置出错", e);
            return Result.createErrorResult("更新轮动配置出错");
        }
    }

    /**
     * 轮动监控
     */
    @RequestMapping(value = "/monitor")
    public String monitor() {
        return "rotation/monitor";
    }

    /**
     * 加载轮动状态
     */
    @ResponseBody
    @RequestMapping("/loadRotationStatus")
    public Result loadRotationStatus(HttpServletRequest request) {
        try {
            return Result.createSuccessResult(this.rotationMonitorService.calcMonitorInfo());
        } catch (Exception e) {
            log.error("加载状态出错", e);
            return Result.createErrorResult("加载状态出错", null);
        }
    }
}
